<?php

/**
 * 微信事件回复模型管理logic
 */

namespace Member\Logic;

class EventLogic extends CommonLogic {
	
	protected $_auto = array(
			array('uid',UID),
	);
	
	/**
	 * (non-PHPdoc)
	 * @see \Member\Logic\BaseLogic::update()
	 */
	public function update($id = 0){
		/* 获取文章数据 */
		$data = $this->create();
		
		
		if($data === false){
			return false;
		}
		
		$data['msgtype'] = I('post.ReplyMsgType');
		$data['arbitrarily'] = I('post.arbitrarily');
		
		//如果是文本消息,添加文本消息
		if($data['msgtype'] == 0){
		    $textmsgLogic = D('textmsg','Logic');
		    $text = I('post.TextContents');
		    $insetid = $textmsgLogic->saveData($text);
		    
		    if(intval($insetid ) <= 0){
		        $this->error('操作失败');
		    }
		    
		    //设置
		    $data['msgtype'] = 'text';
		    $data['msgid'] = $insetid;
		}else{
		    //如果是多图文消息
			$msgtype = I('post.MaterialId');
			
			$TextNews = D('TextNews','Logic');
			$res = $TextNews->savedata($msgtype);
			$data['msgtype'] = $res['msgtype'];
			$data['msgid'] = $res['msgid'];
			
		}
		
		$map = array(
		    'uid'=>UID,
			'event'=>$data['event'],
		);
		//查找之前是否存在相关记录
		$info = $this->where($map)->field('id')->find();
		
		//如果之前存在记录
		if($info['id'] > 0){
			$status = $this->where($map)->save($data);
		}else{
		    $status = $this->add($data);
		}
		
		return $status;
		
		/* 添加或更新数据 */
// 		if(empty($data['id'])){//新增数据
// 			$data['id'] = $id;
// 			$id = $this->add($data);
// 			if(!$id){
// 				$this->error = '新增详细内容失败！';
// 				return false;
// 			}
// 		} else { //更新数据
// 			$status = $this->save($data);
// 			if(false === $status){
// 				$this->error = '更新详细内容失败！';
// 				return false;
// 			}
// 		}
		
		return true;
	}
	
	/**
	 * (non-PHPdoc)
	 * @see \Member\Logic\BaseLogic::autoSave()
	 */
	public function autoSave($id = 0){
		 
	}
	
	/**
	 * 获取当前用户的时间信息
	 */
	public function getUserEvent($event,$userid = UID){
		//查询条件
		$map = array(
		    'event'=>$event,
			'uid'=>$userid,
		);
		//获取用户的信息
	    $userEvent = $this->where($map)->find();
	    
	    if(empty($userEvent) || !isset($userEvent['id'])){
	        return false;
	    }
// 	    dump($userEvent);exit;
	    //如果是文本信息,获取文本信息
	    if($userEvent['msgtype'] == 'text'){
	        $map = array(
	            'uid'=>$userEvent['uid'],
	        	'id'=>$userEvent['msgid'],
	        );
	        
	        $textmsgEvent = D('Textmsg','Logic');
	        //获取文本系信息
	        $textmsg = $textmsgEvent->where($map)->find();
// 	        dump($textmsg);exit;
	        $userEvent['textmsg'] = $textmsg;
	    }
	    
	    return $userEvent;
	}
}